ECAPIHOST = {}

registe_ecs_api = (api_list, synchronous)->
	ECSAPI = ->
		@action = {context: _env.pid}
		@

	ECSAPI:: = {}

	for domain of api_list
		ECSAPI::[domain] = (add_action)->
		for action in api_list[domain]
			ECSAPI::[action] = (call_with_params)->

	(->
		deviceCallSynchronous = (self, api, query) ->
			__ecs_script_api api, query, self.action, null

		deviceCallAsynchronous = (self, api, query) ->
			new Promise (resolve, reject) ->__ecs_script_api api, query, self.action, resolve

		addParams = (self, action, query) ->
			self.action[action] = query or	null
			self.action.api = action
			self

		makeAPI = (orig_api) ->
			add_action_fn = ((add_action) ->).toString()
			call_with_params_fn = ((call_with_params) ->).toString()

			orig_api = orig_api.prototype
			for key of orig_api
				fn_str = orig_api[key].toString()
				if fn_str == add_action_fn
					orig_api[key] = ((key) -> (query) -> addParams @, key, query) key
				else if fn_str == call_with_params_fn
					if synchronous
						orig_api[key] = ((key) -> () -> deviceCallSynchronous @, key, arguments) key
					else
						orig_api[key] = ((key) -> () -> deviceCallAsynchronous @, key, arguments) key

			null

		makeAPI(ECSAPI)
	) null
	ECSAPI

@ecs_registe_synchronous_api = (api_list,api_name)->
	if typeof ECAPIHOST[api_name] == "undefined" then ECAPIHOST[api_name] = registe_ecs_api api_list, true 
	else ECAPIHOST[api_name][api_key] = api_value for api_key,api_value of registe_ecs_api api_list, true
	if api_name then @[api_name] = -> new ECAPIHOST[api_name] else -> new  ECAPIHOST[api_name]
	
@ecs_registe_asynchronous_api = (api_list,api_name)->
	# console.log api_name,api_list
	if typeof ECAPIHOST[api_name] == "undefined" then ECAPIHOST[api_name] = registe_ecs_api api_list, false 
	else ECAPIHOST[api_name][api_key] = api_value for api_key,api_value of registe_ecs_api api_list, false
	if api_name then @[api_name] = -> new ECAPIHOST[api_name] else -> new  ECAPIHOST[api_name]